using System;
using System.Drawing;
using System.IO;

namespace WeChatFileManagementWinApp
{
    /// <summary>
    /// 微信文件类，表示一个微信文件对象
    /// </summary>
    public class WeChatFile : IDisposable
    {
        private bool _iconLoaded = false;
        private Image _icon;
        private readonly Image _defaultIcon;
        private byte[] _iconData;
        private bool _isDisposed;

        /// <summary>
        /// 初始化WeChatFile实例
        /// </summary>
        /// <param name="loadIconImmediately">是否立即加载图标</param>
        public WeChatFile()
        {
            _defaultIcon = SystemIcons.Application.ToBitmap();
            LoadIcon();
        }

        /// <summary>
        /// 使用文件路径初始化WeChatFile实例
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="loadIconImmediately">是否立即加载图标</param>
        public WeChatFile(string path, bool loadIconImmediately = true)
        {
            Path = path;
            Name = System.IO.Path.GetFileName(path);
            Extension = System.IO.Path.GetExtension(path).ToLower();
            _defaultIcon = SystemIcons.Application.ToBitmap();

            // 设置文件的最后修改时间
            if (File.Exists(path))
            {
                var fileInfo = new FileInfo(path);
                LastWriteTime = fileInfo.LastWriteTime;
                LastModified = fileInfo.LastWriteTime;
                Size = fileInfo.Length;
            }

            if (loadIconImmediately)
            {
                LoadIcon();
            }
        }

        /// <summary>
        /// 从文件路径创建WeChatFile对象
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="loadIconImmediately">是否立即加载图标</param>
        /// <param name="iconData">可选的图标数据，如果提供则使用此数据而不是重新加载图标</param>
        public WeChatFile(string filePath, bool loadIconImmediately = true, byte[] iconData = null)
        {
            if (string.IsNullOrEmpty(filePath))
                throw new ArgumentNullException(nameof(filePath));

            Path = filePath;
            Name = System.IO.Path.GetFileName(filePath);
            Extension = System.IO.Path.GetExtension(filePath).ToLower();
            LastWriteTime = File.GetLastWriteTime(filePath);
            if (File.Exists(filePath))
                Size = new FileInfo(filePath).Length;

            if (iconData != null)
            {
                _iconData = iconData;
                LoadIconFromData();
            }
            else if (loadIconImmediately)
            {
                LoadIcon();
            }
        }

        /// <summary>
        /// 文件名
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 文件图标
        /// </summary>
        public Image Icon
        {
            get
            {
                if (!_iconLoaded)
                {
                    LoadIcon();
                }
                return _icon ?? _defaultIcon;
            }
            private set
            {
                if (_icon != null && _icon != _defaultIcon)
                {
                    _icon.Dispose();
                }
                _icon = value;
            }
        }

        /// <summary>
        /// 文件扩展名
        /// </summary>
        public string Extension { get; set; }

        /// <summary>
        /// 文件完整路径
        /// </summary>
        public string Path { get; set; }

        /// <summary>
        /// 搜索日期
        /// </summary>
        public DateTime SearchDate { get; set; }

        /// <summary>
        /// 文件大小（字节）
        /// </summary>
        public long Size { get; set; }

        /// <summary>
        /// 最后修改时间
        /// </summary>
        public DateTime LastModified { get; set; }
        /// <summary>
        /// 最后写入时间
        /// </summary>
        public DateTime LastWriteTime { get; set; }

        /// <summary>
        /// 计算机名称
        /// </summary>
        public string ComputerName { get; set; }

        /// <summary>
        /// 获取图标的字节数组数据
        /// </summary>
        public byte[] GetIconData()
        {
            if (_iconData != null)
                return _iconData;

            if (_icon != null)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    _icon.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    _iconData = ms.ToArray();
                    return _iconData;
                }
            }

            return null;
        }

        /// <summary>
        /// 从字节数组数据加载图标
        /// </summary>
        private void LoadIconFromData()
        {
            if (_iconData != null)
            {
                try
                {
                    using (MemoryStream ms = new MemoryStream(_iconData))
                    {
                        _icon = Image.FromStream(ms);
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"从数据加载图标失败: {ex.Message}");
                    _icon = null;
                    _iconData = null;
                }
            }
        }

        /// <summary>
        /// 加载文件图标
        /// </summary>
        public void LoadIcon()
        {
            if (_icon == null && _iconData == null)
            {
                _icon = FileOperationHelper.GetFileIcon(Path, Extension);
                if (_icon != null)
                {
                    // 保存图标数据
                    using (MemoryStream ms = new MemoryStream())
                    {
                        _icon.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                        _iconData = ms.ToArray();
                    }
                }
            }
            else if (_icon == null && _iconData != null)
            {
                LoadIconFromData();
            }
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            if (!_isDisposed)
            {
                if (_icon != null)
                {
                    _icon.Dispose();
                    _icon = null;
                }
                _iconData = null;
                _isDisposed = true;
            }
        }

        /// <summary>
        /// 打开文件
        /// </summary>
        /// <returns>是否成功打开</returns>
        public bool Open()
        {
            return FileOperationHelper.OpenFile(Path);
        }

        /// <summary>
        /// 打开文件所在文件夹
        /// </summary>
        /// <returns>是否成功打开</returns>
        public bool OpenLocation()
        {
            return FileOperationHelper.OpenFileLocation(Path);
        }

        /// <summary>
        /// 显示文件属性
        /// </summary>
        /// <returns>是否成功显示</returns>
        public bool ShowProperties()
        {
            return FileOperationHelper.ShowFileProperties(Path);
        }

        /// <summary>
        /// 复制文件到剪贴板
        /// </summary>
        /// <returns>是否成功复制</returns>
        public bool CopyToClipboard()
        {
            return FileOperationHelper.CopyFileToClipboard(Path);
        }

        /// <summary>
        /// 复制文件名到剪贴板
        /// </summary>
        /// <returns>是否成功复制</returns>
        public bool CopyNameToClipboard()
        {
            return FileOperationHelper.CopyFileNameToClipboard(Path);
        }

        /// <summary>
        /// 复制文件路径到剪贴板
        /// </summary>
        /// <returns>是否成功复制</returns>
        public bool CopyPathToClipboard()
        {
            return FileOperationHelper.CopyFilePathToClipboard(Path);
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <returns>是否成功删除</returns>
        public bool Delete()
        {
            return FileOperationHelper.DeleteFile(Path);
        }
    }
}